class Solution {
public:
   void reverse_again(string &s,int begin,int find){
        if(begin >= find){
            return;
        }
        size_t lh = begin, rh = find;
        while(lh < rh){
           swap(s[lh++], s[rh--]);
       }
       return;
    } //reverse the substring [begin, find]
    void reverseWords(string &s) {
        if(s.length() == 0){
			return;
		}

		if(s.length() == 1){
			s = (s[0]==' ') ? "":s;
			return;
		}

		//disgard " " at begin and end of a string
		int begin=0, end=s.length()-1;
		while(s[begin] == ' '){
			begin++;
		}
		while(s[end] == ' '){
			end--;
		}

		//string has no words
		if(begin > end){
			s = "";
			return;
		}
		if(begin <= end){
			s = s.substr(begin, end-begin+1);
		}
	
		//swap string
		begin = 0;
		end = s.length()-1;
		while(begin < end){
			swap(s[begin++], s[end--]);
		}

		//swap words back
		begin = 0;
		end = 0;
		while(end < s.length()){
			while(end < s.length() && s[end] != ' '){
				end++;
			}
			if(begin < end){
				reverse_again(s, begin, end-1);
				if(end < s.length()){
					begin = end+1;
					end++;
				}
			}else{
				//erase continuous " " char
				s.erase(s.begin()+begin);
			}
			
		}
		return;
    }
   
   
};
